"""
客户管理序列化器（后台管理）
"""
from rest_framework import serializers
from django.contrib.auth.models import User
from pecco_site.models import UserProfile, UserAddress


class CustomerProfileSerializer(serializers.ModelSerializer):
    """客户资料序列化器
    注意：地址信息优先返回用户的默认收货地址（UserAddress），
    若无默认地址，则回退到 UserProfile 中的静态地址字段。
    """
    company = serializers.CharField(required=False, allow_blank=True)
    address_line1 = serializers.SerializerMethodField()
    address_line2 = serializers.SerializerMethodField()
    city = serializers.SerializerMethodField()
    state = serializers.SerializerMethodField()
    postal_code = serializers.SerializerMethodField()
    country = serializers.SerializerMethodField()
    phone = serializers.SerializerMethodField()
    total_orders = serializers.SerializerMethodField()
    total_spent = serializers.SerializerMethodField()

    class Meta:
        model = UserProfile
        fields = [
            'phone', 'avatar', 'company',
            'address_line1', 'address_line2',
            'city', 'state', 'postal_code', 'country',
            'total_orders', 'total_spent', 'preferred_language',
            'newsletter_subscribed', 'created_at', 'updated_at'
        ]

    def _get_default_address(self, obj: UserProfile):
        if not hasattr(obj, 'user'):
            return None
        default_addr = obj.user.addresses.filter(is_default=True).first()
        if default_addr is None:
            # 没有默认地址则取最近创建的一个地址
            default_addr = obj.user.addresses.order_by('-created_at').first()
        return default_addr

    def get_address_line1(self, obj: UserProfile):
        if obj.address_line1:
            return obj.address_line1
        addr = self._get_default_address(obj)
        return addr.address_line1 if addr else ''

    def get_address_line2(self, obj: UserProfile):
        if obj.address_line2:
            return obj.address_line2
        addr = self._get_default_address(obj)
        return addr.address_line2 if addr else ''

    def get_city(self, obj: UserProfile):
        if obj.city:
            return obj.city
        addr = self._get_default_address(obj)
        return addr.city if addr else ''

    def get_state(self, obj: UserProfile):
        if obj.state:
            return obj.state
        addr = self._get_default_address(obj)
        return addr.state if addr else ''

    def get_postal_code(self, obj: UserProfile):
        if obj.postal_code:
            return obj.postal_code
        addr = self._get_default_address(obj)
        return addr.postal_code if addr else ''

    def get_country(self, obj: UserProfile):
        if obj.country:
            return obj.country
        addr = self._get_default_address(obj)
        return addr.country if addr else ''

    def get_phone(self, obj: UserProfile):
        if obj.phone:
            return obj.phone
        addr = self._get_default_address(obj)
        return addr.phone if addr else ''


    def get_total_orders(self, obj: UserProfile):
        """获取客户的总订单数（只统计已完成的订单）"""
        if not hasattr(obj, 'user'):
            return 0
        from pecco_site.models import Order
        return Order.objects.filter(user=obj.user, status='completed').count()

    def get_total_spent(self, obj: UserProfile):
        """获取客户的总消费金额（只统计已完成的订单）"""
        if not hasattr(obj, 'user'):
            return '0.00'
        from pecco_site.models import Order
        from django.db.models import Sum
        total = Order.objects.filter(
            user=obj.user,
            status='completed'
        ).aggregate(total=Sum('total_price'))['total']
        return str(total) if total else '0.00'


class CustomerListSerializer(serializers.ModelSerializer):
    """客户列表序列化器"""
    profile = CustomerProfileSerializer(read_only=True, allow_null=True)
    full_name = serializers.SerializerMethodField()
    
    class Meta:
        model = User
        fields = [
            'id', 'username', 'email', 'first_name', 'last_name',
            'full_name', 'is_active', 'date_joined', 'last_login', 'profile'
        ]
    
    def get_full_name(self, obj):
        """获取全名"""
        return f"{obj.first_name} {obj.last_name}".strip() or obj.username


class CustomerDetailSerializer(serializers.ModelSerializer):
    """客户详情序列化器"""
    profile = CustomerProfileSerializer()
    addresses = serializers.SerializerMethodField()
    
    class Meta:
        model = User
        fields = [
            'id', 'username', 'email', 'first_name', 'last_name',
            'is_active', 'date_joined', 'last_login', 'profile', 'addresses'
        ]
        read_only_fields = ['id', 'date_joined', 'last_login']
    
    def update(self, instance, validated_data):
        """更新客户信息"""
        profile_data = validated_data.pop('profile', None)
        
        # 更新User字段
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()
        
        # 更新Profile字段
        if profile_data and hasattr(instance, 'profile'):
            profile = instance.profile
            for attr, value in profile_data.items():
                setattr(profile, attr, value)
            profile.save()
        
        return instance

    def get_addresses(self, user: User):
        """返回用户的所有地址，已按默认优先、创建时间倒序排序（见模型 Meta.ordering）"""
        addresses = user.addresses.all()
        return [
            {
                'id': a.id,
                'first_name': a.first_name,
                'last_name': a.last_name,
                'company': a.company,
                'address_line1': a.address_line1,
                'address_line2': a.address_line2,
                'city': a.city,
                'state': a.state,
                'postal_code': a.postal_code,
                'country': a.country,
                'phone': a.phone,
                'is_default': a.is_default,
                'created_at': a.created_at,
                'updated_at': a.updated_at,
            }
            for a in addresses
        ]


class CustomerStatsSerializer(serializers.Serializer):
    """客户统计序列化器"""
    total_customers = serializers.IntegerField()
    active_customers = serializers.IntegerField()
    newsletter_subscribers = serializers.IntegerField()
    total_orders = serializers.IntegerField()
    total_revenue = serializers.DecimalField(max_digits=10, decimal_places=2)
